package com.sskj.givecoin.common.widget;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import com.sskj.givecoin.R;
import com.sskj.givecoin.common.adapter.BaseAdapter;

public class SelectView extends android.support.v7.widget.AppCompatTextView {

    PopupWindow popupWindow;


    private RecyclerView.Adapter mAdapter;

    private OnSelectListener listener;

    public SelectView(Context context) {
        super(context);
        init();
    }

    public SelectView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public SelectView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        //点击弹出popupWindow
        setOnClickListener(v -> {
            showPopupWindow();
        });
    }

    private void showPopupWindow() {
        if (popupWindow == null) {
            View mView = LayoutInflater.from(getContext()).inflate(R.layout.select_view, null);
            RecyclerView recyclerView = mView.findViewById(R.id.select);
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            recyclerView.setAdapter(mAdapter);
            if (mAdapter instanceof BaseAdapter) {
                BaseAdapter adapter = (BaseAdapter) mAdapter;
                adapter.setOnItemClickListener((adapter1, view, position) -> {
                    if (listener != null) {
                        listener.onSelectListener(this, position, (BaseAdapter) adapter1);
                    }
                });
            }
            popupWindow = new PopupWindow(mView, getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT, true);
            popupWindow.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(getContext(),R.color.background)));
            popupWindow.setTouchable(true);
            popupWindow.setOutsideTouchable(true);

        }
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        } else {
            popupWindow.showAsDropDown(this);
        }
    }


    public void dismiss() {
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
    }


    public void setOnSelectListener(OnSelectListener listener) {
        this.listener = listener;
    }

    public <T> void  bindAdapter(BaseAdapter<T> adapter) {
        this.mAdapter = adapter;
    }


    public interface OnSelectListener {
        void onSelectListener(SelectView view, int position, BaseAdapter adapter);
    }

}
